package com.alibaba.nacos.console.config;

import com.dist.dcc.security.http.filter.HttpSecurityFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static java.lang.Boolean.FALSE;

@Configuration
@EnableConfigurationProperties(HttpSecurityProperties.class)
public class HttpSecurityConfig {

    @Autowired
    HttpSecurityProperties httpSecurityProperties;

    @Bean
    public FilterRegistrationBean<HttpSecurityFilter> httpSecurityFilterRegistration() {
        FilterRegistrationBean<HttpSecurityFilter> filterRegistrationBean = new FilterRegistrationBean<HttpSecurityFilter>();
        filterRegistrationBean.setFilter(httpSecurityFilter());
        filterRegistrationBean.setOrder(900);
        filterRegistrationBean.setName("httpSecurityFilter");
        return filterRegistrationBean;
    }

    private HttpSecurityFilter httpSecurityFilter() {
        HttpSecurityFilter filter = new HttpSecurityFilter();
        filter.setAllowedMethods(httpSecurityProperties.getAllowedMethods());
        filter.setContentSecurityPolicyEnabled(httpSecurityProperties.isCspEnabled());
        filter.setContentSecurityPolicyHeaderValue(httpSecurityProperties.getCspValue());
        filter.setFrameOptionsEnabled(httpSecurityProperties.isFrameOptionsEnabled());
        filter.setFrameOptionsHeaderValue(httpSecurityProperties.getFrameOptionsHeaderValue());
        filter.setContentTypeOptionsEnabled(httpSecurityProperties.isContentTypeOptionsEnabled());
        filter.setCookieHttpOnlyEnabled(FALSE);
        filter.setXssProtectionEnabled(httpSecurityProperties.isXssProtectionEnabled());
        HttpSecurityFilter.setXssProtectionEscapeChars(httpSecurityProperties.getXssProtectionEscapeChars());
        filter.setStrictTransportSecurityEnabled(httpSecurityProperties.isStrictTransportSecurityEnabled());
        filter.setCookieHttpOnlyEnabled(httpSecurityProperties.isCookieHttpOnly());
        return filter;
    }

}
